from maix import camera, display, image, nn, app, uart, time
from maix._maix.image import COLOR_BLUE

'''
协议
检测到最开始的目标药房号：0x0a 0x0b 0x01 target 0x0c
在路上检测到的目标药房号：0x0a 0x0b 0x02 (0x00:L、0x01:R) 0x0c
'''
devices = uart.list_devices()
serial = uart.UART(devices[0], 115200)

detector = nn.YOLOv5(model="/root/models/model-120311(number)/model_120311.mud")

cam = camera.Camera(640,480, detector.input_format())
cam.skip_frames(30) 
dis = display.Display()
#************************************************************************************
First = ['one','two','three','four','five','eight','seven','six']
number_name = [' one',' two',' three',' four',' five',' six',' seven',' eight']
detected_number = None  # 初始化变量来存储第一次识别到的数字
Left_point = [0,0]
right_point = [0,0]
centre_dot = 0
tr_dir = 0
target = 0              # 目标药房
direction = 0           # 转弯方向
L = 1                   # 左转标志
R = 2                   # 右转标志
datadict = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0}     # 保存每个数字对应的出现次数
coordict = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0}     # 保存数字的坐标数据
count = 0               # 统计次数
#************************************************************************************

# 画图
def draw_roi(img):
    global cam,target,direction
    img.draw_line(cam.width()//2,0,cam.width()//2,cam.height(),image.COLOR_GREEN, 3) 
    img.draw_string(0, 4, "targer:{}".format(target), color = image.COLOR_BLUE, scale = 2)
    img.draw_string(0, 28*1, "direction:{}".format(direction), color = image.COLOR_BLUE, scale = 2)

# 串口发送
def Uart(command):
    if len(command) >= 2:
        data = bytes([0x3c,0x1d,command[0],command[1],0x4b])
        serial.write(data)

# 检测数字
def detector_number(img):
    global number_name,target,tr_dir,cross_dir,direction,L,R,datadict,coordict,count
    objs = detector.detect(img, conf_th = 0.7, iou_th = 0.45)
    for obj in objs:
        img.draw_rect(obj.x, obj.y, obj.w, obj.h, color = image.COLOR_RED)
        msg = f'{detector.labels[obj.class_id]}: {obj.score:.2f}'       # 格式化字符串字面量（f-string）
        img.draw_string(obj.x, obj.y, msg, color = image.COLOR_RED)     # 根据detector.labels[obj.class_id]的值和obj.score的值（格式化为两位小数）来动态构建字符串msg。
        number = detector.labels[obj.class_id]
        index = 0
        for n in number_name:
            if number in n:
                index = number_name.index(n)+1
                break
        # if target == 0:
        #     target = index
        #     Uart([1,target])
        # else :
        #     if index == target:
        #         if obj.x+obj.w/2 > cam.width()//2:
        #             direction = R
        #         else :
        #             direction = L
        #             Uart([2,direction])
        # 统计
        datadict[index] += 1
        coordict[index] = obj
    # 判决
    count += 1
    if count >= 10:
        for number in datadict:
            if datadict[number] >= 5:
                if target == 0:
                    target = number
                    for t in range(0,5):
                        Uart([1,target])
                        time.sleep_ms(10)
                else :
                    if number == target:
                        if coordict[number].x+coordict[number].w/2 > cam.width()//2:
                            direction = R
                        else :
                            direction = L
                        Uart([2,direction])
        # 更新数据
        count = 0
        datadict = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0}     
        coordict = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0, 7:0, 8:0}     

while not app.need_exit():
    img = cam.read()
    detector_number(img)
    draw_roi(img)
    dis.show(img)
